package com.zhen.aikan.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhen.aikan.constant.ScheduleConstants;
import com.zhen.aikan.entity.Scheduled;
import com.zhen.aikan.mapper.ScheduledMapper;
import com.zhen.aikan.service.IScheduledService;
import com.zhen.aikan.util.ScheduleUtils;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author LiJiaZhen
 * @date 2023/9/18 18:26
 */
@Service
public class IScheduledServiceImpl extends ServiceImpl<ScheduledMapper, Scheduled> implements IScheduledService {
    @Autowired
    private Scheduler scheduler;

    /**
     * 项目启动时，初始化定时器 主要是防止手动修改数据库导致未同步到定时任务处理（注：不能手动修改数据库ID和任务组名，否则会导致脏数据）
     */
    @PostConstruct
    public void init() throws Exception {
        scheduler.clear();
        List<Scheduled> scheduleds = baseMapper.selectList(null);
        for (Scheduled job : scheduleds) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
    }

    /**
     * 新增任务
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertJob(Scheduled job) throws Exception {
        // 先将任务设置为暂停状态
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = baseMapper.insert(job);
        if (rows > 0) {
            ScheduleUtils.createScheduleJob(scheduler, job);
        }
        return rows;
    }

    @Override
    public void run(Scheduled job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        Scheduled properties = getById(jobId);
        // 参数
        JobDataMap dataMap = new JobDataMap();
        dataMap.put(ScheduleConstants.TASK_PROPERTIES, properties);
        scheduler.triggerJob(ScheduleUtils.getJobKey(jobId, jobGroup), dataMap);
    }


    @Override
    public int pauseJob(Scheduled job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.PAUSE.getValue());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            scheduler.pauseJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    public int resumeJob(Scheduled job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        job.setStatus(ScheduleConstants.Status.NORMAL.getValue());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            scheduler.resumeJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    public int deleteJob(Scheduled job) throws SchedulerException {
        Long jobId = job.getJobId();
        String jobGroup = job.getJobGroup();
        int rows = baseMapper.deleteById(jobId);
        if (rows > 0) {
            scheduler.deleteJob(ScheduleUtils.getJobKey(jobId, jobGroup));
        }
        return rows;
    }

    @Override
    public int changeStatus(Scheduled job) throws SchedulerException {
        int rows = baseMapper.updateById(job);
        if (rows == 0) {
            return rows;
        }
        //更新成功，需要改调度器内任务的状态
        //拿到整个任务
        Scheduled job2 = baseMapper.selectById(job.getJobId());
        //根据状态来启动或者关闭
        if (ScheduleConstants.Status.NORMAL.getValue().equals(job2.getStatus())) {
            rows = resumeJob(job2);
        } else if (ScheduleConstants.Status.PAUSE.getValue().equals(job2.getStatus())) {
            rows = pauseJob(job2);
        }
        return rows;
    }

    @Override
    public int updateJob(Scheduled job) throws Exception {
        Scheduled properties = baseMapper.selectById(job.getJobId());
        int rows = baseMapper.updateById(job);
        if (rows > 0) {
            updateSchedulerJob(job, properties.getJobGroup());
        }
        return rows;
    }

    public void updateSchedulerJob(Scheduled job, String jobGroup) throws Exception {
        Long jobId = job.getJobId();
        // 判断是否存在
        JobKey jobKey = ScheduleUtils.getJobKey(jobId, jobGroup);
        if (scheduler.checkExists(jobKey)) {
            // 防止创建时存在数据问题 先移除，然后在执行创建操作
            scheduler.deleteJob(jobKey);
        }
        ScheduleUtils.createScheduleJob(scheduler, job);
    }


    @Override
    public boolean checkCronExpressionIsValid(String cronExpression) {
        return false;
    }
}
